import { getCategoriesApi } from "@/api/home";
import { topCategories } from "@/api/constants";

let category = {
  namespaced: true,
  state() {
    return {
      // 存储分类列表
      list: topCategories.map((item) => ({ name: item })),
    };
  },
  mutations: {
    // 设置分类列表数据
    setCategories(state, data) {
      state.list = data;
    },
    open(state, id) {
      const index = state.list.findIndex((item) => item.id === id);
      state.list[index].open = true;
    },
    close(state, id) {
      const index = state.list.findIndex((item) => item.id === id);
      state.list[index].open = false;
    },
  },
  actions: {
    // 获取分类列表数据
    getCategories({ commit }) {
      getCategoriesApi().then((data) => {
        // 新加入一个open属性
        data.result.forEach((item) => {
          item.open = false;
        });
        commit("setCategories", data.result);
      });
    },
  },
};
export default category;
